/*
 * Copyright @ 2024 weili23
 * com.sky.service.impl 17:06
 * All right reserved.
 */

package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;


/**
 * @desc:
 * @author: weili23
 * @createTime: 2024/10/25 17:06
 * @version: v1.0
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private DishMapper dishMapper;

    @Resource
    private SetmealDishMapper setmealDishMapper;

    @Resource
    private RedisTemplate redisTemplate;
    private static final String DISH_KEY="DISH:";
    @Override
    public void saveDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        this.save(dish);
        List<DishFlavor> flavor = dishDTO.getFlavors();
        if(CollectionUtils.isNotEmpty(flavor) && flavor.size()>0){
            flavor.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
                dishFlavorMapper.insert(dishFlavor);
            });
            //保存口味表数据
        }
        //清除redis缓存
        redisTemplate.delete(DISH_KEY+dishDTO.getCategoryId());
    }

    @Override
    public Page<DishVO> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        Page<DishVO> page =new Page();
        page.setSize(dishPageQueryDTO.getPageSize());
        page.setCurrent(dishPageQueryDTO.getPage());
        Page<DishVO> page1 = dishMapper.queryPage(page,dishPageQueryDTO);
        return page1;
    }

    @Override
    @Transactional(rollbackFor =  Exception.class)
    public void deleteDish(String ids) {
        // 使用 split 方法将字符串分割成数组
        String[] idArray = ids.split(",");
        // 将数组转换为列表
        List<String> idList = Arrays.asList(idArray);
        //先查询售卖状态是不是停售，
        for (String id: idList) {
            Dish dish = this.getById(id);
            if(dish !=null){
                if(dish.getStatus() == 1){
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
            }
            //查询是否关联了套餐
            QueryWrapper<SetmealDish> qw = new QueryWrapper<>();
            qw.eq(SetmealDish.DISH_ID,Long.parseLong(id));
            List<SetmealDish> setmealDishes = setmealDishMapper.selectList(qw);
            if(CollectionUtils.isNotEmpty(setmealDishes) && setmealDishes.size()>0){
                //当前菜品关联了套餐,不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        //批量删除
        this.removeBatchByIds(idList);
        //批量删除口味表
        dishFlavorMapper.deleteBatchByIds(idList);
        //清除所有缓存
        Set keys = redisTemplate.keys("DISH:*");
        redisTemplate.delete(keys);
    }

    @Override
    public DishVO selectById(String id) {
        DishVO dishVO = new DishVO();
        //查询菜品详情
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish,dishVO);
        //根据dishid查询口味表详情
        QueryWrapper<DishFlavor> qw = new QueryWrapper<>();
        qw.eq(DishFlavor.DISH_ID,id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(qw);
        if(CollectionUtils.isNotEmpty(dishFlavors) && dishFlavors.size()>0){
            dishVO.setFlavors(dishFlavors);
        }
        return dishVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDishWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        this.updateById(dish);
        //先删除关联的口味数据，在插入
        QueryWrapper<DishFlavor> qw = new QueryWrapper<>();
        qw.eq(DishFlavor.DISH_ID,dishDTO.getId());
        dishFlavorMapper.delete(qw);
        //判断集合是否为空，循环遍历
        if(CollectionUtils.isNotEmpty(dishDTO.getFlavors()) && dishDTO.getFlavors().size()>0){
            dishDTO.getFlavors().forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
                dishFlavorMapper.insert(dishFlavor);
            });
        }

        //清除redis缓存
        redisTemplate.delete(DISH_KEY+dishDTO.getCategoryId());
    }

    @Override
    public void onSaleOrStopSale(Long id, Integer status) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        //根据id修改菜品起售、停售
        this.updateById(dish);
        //清除所有缓存
        Set keys = redisTemplate.keys("DISH:*");
        redisTemplate.delete(keys);

    }

    @Override
    public List<Dish> selectListByGateroyId(Long categoryId) {
        List<Dish> list = this.lambdaQuery().eq(Dish::getCategoryId, categoryId)
                .orderByDesc(Dish::getCreateTime).list();
        return list;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //从redis中获取
        List<DishVO> dishVo = (List<DishVO>) redisTemplate.opsForValue().get(DISH_KEY + dish.getCategoryId());
        if(CollectionUtils.isNotEmpty(dishVo)){
            return dishVo;
        }
        List<Dish> dishList = this.lambdaQuery().eq(Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, dish.getStatus()).list();

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据dishid查询口味表详情
            List<DishFlavor> flavors = Db.lambdaQuery(DishFlavor.class).eq(DishFlavor::getDishId, d.getId()).list();
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //查询之后保存到redis中
        redisTemplate.opsForValue().set(DISH_KEY+dish.getCategoryId(),dishVOList);
        return dishVOList;
    }

}
